<?php


namespace Soen\Container;


use http\Exception\RuntimeException;
use Soen\Container\Aop\Aop;
use Soen\Filesystem\Dir;
use Soen\Filesystem\File;

class Server
{
    public $configComponents;
    public $configArray;
    public $filesystem;
    function __construct($path)
    {
        $this->filesystem = (new File())->createFilesystemIterator($path);
    }

    /**
     * 载入所有服务配置
     * @return array
     */
    function load(){
        $this->configArray = $this->filesystem->readArrayFilesDeep();
        $this->parse($this->configArray);
        return $this->configComponents;
    }

    function parse($configArray){
        try{
            foreach ($configArray as $config){
                if(isset($this->configComponents[$config['name']])){
                    throw new \RuntimeException('组件名:' . $config['name'] . ',该组件已存在!');
                }
                if (isset($config['propertys']) && !empty($config['propertys'])) {
                    $aop = new Aop($config['class']);
                    $classPathName = $aop->setPropertys($config['propertys']);
                    $config['class'] = $classPathName;
                }
                if(!isset($config['init']) || !(string)$config['init']){
	                $reflection = new \ReflectionClass($config['class']);
	                if($reflection->hasMethod('init')){
		                $config['init'] = 'init';
	                }
                }
                $this->configComponents[$config['name']] = $config;
            }
        }catch (\Throwable $e){
            throw new \RuntimeException($e->getMessage());
        }

    }


}